package luo.filter;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.SignatureException;
import luo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.LogRecord;

import static com.sun.org.apache.xpath.internal.compiler.Token.contains;

/**
 * @Description: 添加jwt验证过滤器
 * @Author:let_free
 * @Date:2024/10/3/13:17
 **/
@Component
public class JwtFilter extends OncePerRequestFilter {
    @Autowired
    @Qualifier("handlerExceptionResolver")  //需要显示指定异常处理器  否则报错多个bean
    private HandlerExceptionResolver resolver;
    private static final Set<String> URL_SET = new HashSet<>();

    static {
        URL_SET.add("/login/login");
        URL_SET.add("/doc.html");
        URL_SET.add("/favicon.ico");
        URL_SET.add("/swagger-resources");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestUrl = request.getRequestURI();
//        检查是否在白名单  在就放行
        if (URL_SET.contains(requestUrl) || requestUrl.contains("api-docs") || requestUrl.contains("webjars")||requestUrl.contains("druid")||requestUrl.contains("websocket")) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            resolver.resolveException(request, response, null, new JwtException("当前用户没有登录或者登录状态已经过期"));
            return;
        } else {
            try {
                TokenUtils.validateToken(token);
            } catch (JwtException e) {
                resolver.resolveException(request, response, null, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
